<template>
  <el-dialog
    v-model="dialogVisible"
    
    
    width="40%"
    
    :before-close="handleClose"
    
  >
  <template #header="{  titleId, titleClass }">
    <div class="my-header">
      <h2 :id="titleId" :class="titleClass">欢迎你，看起来你是首次登陆，填写一些基础信息吧</h2>
      <a @click="setForm" :style="{fontSize:'14px'}">如果你不想填写，可以点击此处模板</a>
    </div>
  </template>
  <el-form :model="avatarFile">
    <el-upload
      class="avatar-uploader"
      action="/user/upload-avatar"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </el-form>

      <el-form :model="state.form" :rules="state.rules">
          <el-form-item label="昵称" prop="nickname">
              <el-input v-model="state.form.nickname"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
              <el-input v-model="state.form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱号" prop="email">
              <el-input v-model="state.form.email"></el-input>
          </el-form-item>
          <el-form-item label="部门" prop="department">
              <el-cascader 
              v-model="state.form.departmentId"
              :options="state.options"
              
              @change="handleChange"
            
              clearable />
          </el-form-item>
          
          </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script  setup>
import { onMounted,ref,reactive } from 'vue'
import { ElMessageBox,ElMessage } from 'element-plus'
import useStore from '../../store';
import { ElNotification } from 'element-plus'
import requestMethods from '../../api/api'



const state = reactive({
options: [],
form:{
  nickname:'',
  phone:'',
  email:'',
  departmentId:null
},
userinfo:useStore().user.userinfo,

rules:{
   nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱号', trigger: 'blur' },
      { type: 'email', message: '邮箱号格式不正确', trigger: 'blur' }
    ],
    department: [
      { required: false, message: '请选择部门', trigger: 'blur' }
    ]}
});
const imageUrl = ref('');
const avatarFile = ref(null);
const dialogVisible = ref(false)
const serverUrl = process.env.VUE_APP_AVATAR_API

const submitForm = ()=> {
  requestMethods.initUserInfo(state.form)
    .then(res => {
   
      useStore().user.setUserInfo(res.data)

      ElNotification({
      title: 'Success',
      message: '信息已成功更新',
      type: 'success',
    })

      dialogVisible.value = false
    })
    .catch(error => {
      
      ElNotification({
      title: 'Error',
      message: '保存错误 ' + error,
      type: 'Error',
    })
    })

   

}

onMounted(()=>{
  let showSwitch = useStore().user.userinfo;
  console.log(Object.keys(showSwitch).length>0);
  if(!(Object.keys(showSwitch).length>0)){
    console.log('信息不存在');
    dialogVisible.value = true
  }
  requestMethods.getAllDepartments().then(
      res => {
          state.options = formatData(res.data);
       
      }
  ).catch(error => console.log(error))
 ;
})



const setForm = () => {
 
      state.form.nickname = '张三',
      state.form.phone = "13912345678",
      state.form.email = "2652622@qq.com"



}

const handleClose = () => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      dialogVisible.value = false
    })
    .catch(() => {
      // catch error
    })
}

const handleChange = (val) => {
   console.log(val)

}

const formatData = (data) => {
  return data.map((item) => {
  const newItem = {
    value: item._id,
    label: item.name,
  };
  if (item.children && item.children.length > 0) {
    newItem.children = formatData(item.children);
  }
  return newItem;
});
}

const handleAvatarSuccess = () => {
      imageUrl.value = URL.createObjectURL(avatarFile.value);
      console.log(imageUrl.value);
      ElMessage.success('上传成功');
    };


  const beforeAvatarUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJpgOrPng) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      avatarFile.value = file;

      requestMethods.uploadAvatar(file).then(res=>{
          console.log(res.data);
           // 将 Data URL 绑定到 avatarUrl 属性上，以在 img 标签中显示图片
           state.avatarUrl = `${serverUrl}/${res.data.avatar.replace(/\\/g, '/')}`;
           useStore().user.userinfo.avatar = state.avatarUrl})
           .catch(err => {
            console.log(err)
            })
      handleAvatarSuccess();
      return true;
    };

</script>
<style scoped lang="less">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.el-dialog{
  padding: 40px;

  .el-form{
    padding: 40px;
  }
}
</style>
